import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import type { ApiDetailResponse } from '@/types'

interface FormState<T> {
  data: T
  loading: boolean
  submitting: boolean
}

/**
 * 通用表单管理组合式函数
 * @param initialData 初始表单数据
 * @param saveApi 保存API函数
 * @param rules 表单验证规则
 * @returns 表单状态和操作方法
 */
export function useForm<T extends Record<string, any>>(
  initialData: T,
  saveApi: (data: T) => Promise<ApiDetailResponse<T>>,
  rules?: FormRules
) {
  const formRef = ref<FormInstance>()

  const state = reactive<FormState<T>>({
    data: { ...initialData },
    loading: false,
    submitting: false,
  }) as FormState<T>

  /**
   * 重置表单
   */
  const resetForm = () => {
    state.data = { ...initialData }
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  /**
   * 设置表单数据
   */
  const setFormData = (data: Partial<T>) => {
    Object.assign(state.data, data)
  }

  /**
   * 验证表单
   */
  const validateForm = async (): Promise<boolean> => {
    if (!formRef.value) return false

    try {
      await formRef.value.validate()
      return true
    } catch (error) {
      return false
    }
  }

  /**
   * 提交表单
   */
  const submitForm = async (): Promise<boolean> => {
    const isValid = await validateForm()
    if (!isValid) return false

    try {
      state.submitting = true
      const response = await saveApi(state.data)

      if (response.code === 0) {
        ElMessage.success(state.data.id ? '更新成功' : '创建成功')
        return true
      } else {
        ElMessage.error(response.msg || '保存失败')
        return false
      }
    } catch (error) {
      console.error('提交表单失败:', error)
      ElMessage.error('网络错误，请稍后重试')
      return false
    } finally {
      state.submitting = false
    }
  }

  /**
   * 确认提交（带确认框）
   */
  const confirmSubmit = async (message: string = '确定要保存吗？'): Promise<boolean> => {
    try {
      await ElMessageBox.confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      return await submitForm()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('确认提交失败:', error)
      }
      return false
    }
  }

  return {
    // 表单引用
    formRef,

    // 状态
    formData: state.data,
    loading: state.loading,
    submitting: state.submitting,

    // 方法
    resetForm,
    setFormData,
    validateForm,
    submitForm,
    confirmSubmit,
  }
}
